package com.qf.controller;

import com.qf.entity.Result;
import com.qf.pojo.SysUsers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@RestController
public class UserController {

    @RequestMapping("/doLogin")
    public Result doLogin( SysUsers users){

        try {
            //获取主体对象
            Subject subject = SecurityUtils.getSubject();

            String password = users.getPassword();
            //对用户输入的密码加密
            password = new Md5Hash(password, users.getUsername() , 1024).toString();

            AuthenticationToken token = new UsernamePasswordToken(users.getUsername(), password);
            ((UsernamePasswordToken) token).setRememberMe(true);

            subject.login(token);

            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            System.out.println("未知的用户");
        } catch (CredentialsException e) {
            System.out.println("密码错误");
        }catch (LockedAccountException e) {
            System.out.println("账户已锁定");
        }catch (AuthenticationException e) {
            e.printStackTrace();
        }

        return Result.ok("登录成功");

    }

    @RequestMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }
}

